<!-- <template>
    <div class="boxs">
        <el-card>
            <el-form :model="queryParams" ref="queryForm" :inline="true">
                <el-form-item label="国家">
                    <el-select v-model="queryParams.country" @change="getStatistics">
                        <el-option v-for="item in countryList" :key="item.country" :label="item.country"
                            :value="item.country"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="语言">
                    <el-select v-model="queryParams.language" @change="getStatistics">
                        <el-option v-for="item in languageList" :key="item.language" :label="item.language"
                            :value="item.language"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="时间范围">
                    <el-date-picker v-model="value1" value-format="yyyy-MM-dd" type="daterange" range-separator="-"
                        :start-placeholder="$t('table.start')" :end-placeholder="$t('table.end')"
                        :picker-options="pickerOptions" @change="timeChange">
                    </el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" size="small"
                        @click="getStatistics">{{ $t('table.search') }}</el-button>
                    <el-button icon="el-icon-refresh" size="small"
                        @click="resetQuery">{{ $t('table.reset') }}</el-button>
                </el-form-item>
            </el-form>
            <div style="display: flex;align-items: center;flex-wrap: wrap;margin-top: 50px;">
                <div class="police-count1" ref="chart1"></div>
                <div class="police-count2" ref="chart2"></div>
                <div class="police-count3" ref="chart3"></div>
                <div class="police-count4" ref="chart4"></div>
                <div class="police-count5" ref="chart5"></div>
                <div class="police-count6" ref="chart6"></div>
                <div class="police-count7" ref="chart7"></div>
                <div class="police-count8" ref="chart8"></div>
                <div class="police-count9" ref="chart9"></div>
                <div class="police-count10" ref="chart10"></div>
            </div>
        </el-card>
    </div>
</template>
<script>


import { getFaceTokens, getTokens } from "@/api/beauty";
import { getList, getCountryList, getLanguageList } from "@/api/iptv";
import pk from "@/utils/pk";
import * as XLSX from "xlsx";
export default {
    name: "subscription",
    data() {
        return {
            currentList: [],
            countryList: [],
            languageContent: '',
            goalLanguage: "zh_CN",
            languageList: [],
            translateLoading: false,
            pkList: [],

            queryParams: {
                dateRange: {
                    start: '',
                    end: ''
                },
                country: '',
                language: '',
            },
            total: 0,
            loading: false,
            addLoading: false,
            moreArr: [],
            dialogVisible: false,
            form: {
                comment_type: "",
            },
            search: "",
            rules: {
                comment_type: [
                    { required: true, message: "请输入类型", trigger: "blur" },
                ],
            },
            value1: "",
            chartContainer1: null,
            option1: {},
            chartData: [],
            chartContainer2: null,
            option2: {},
            chartData2: [],
            chartContainer3: null,
            option3: {},
            chartData3: [],
            chartContainer4: null,
            option4: {},
            chartData4: [],
            chartContainer5: null,
            option5: {},
            chartData5: [],
            chartContainer6: null,
            option6: {},
            chartData6: [],
            chartContainer7: null,
            option7: {},
            chartData7: [],
            chartContainer8: null,
            option8: {},
            chartData8: [],
            chartContainer9: null,
            option9: {},
            chartData9: [],
            chartContainer10: null,
            option10: {},
            chartData10: [],
            isLoading1: true,
            chart1: null,
            chart2: null,
            chart3: null,
            chart4: null,
            chart5: null,
            chart6: null,
            chart7: null,
            chart8: null,
            chart9: null,
            chart10: null,

            loadingOption: {
                text: '',
                color: '#409eff',
                maskColor: 'rgba(255, 255, 255, 0.8)',
                zlevel: 0
            },
            pk: '',
            pickerOptions: {

            },
            invalidDateRange: false,
            str: '近30天',
            conversionRateMean: 0

        };
    },
    created() {

    },

    mounted() {
        this.pickerOptions = {
            onPick: ({ maxDate, minDate }) => {
                if (minDate && maxDate) {
                    // 验证选择的日期范围
                    const oneMonthLater = new Date(minDate);
                    oneMonthLater.setMonth(oneMonthLater.getMonth() + 1);

                    if (maxDate > oneMonthLater) {
                        // 如果超过一月范围
                        this.$nextTick(() => {
                            alert('选择的日期范围不能超过一个月');
                            this.value1 = []
                            // 立即重置 maxDate 以取消选择
                            this.invalidDateRange = true; // 设置标志位为 true
                        });
                    } else {
                        this.invalidDateRange = false; // 设置标志位为 false
                    }
                }
            }
        };
        const { pk } = this.$route.query;
        this.queryParams.pk = pk
        this.pk = pk
        this.getStatistics();
        this.getCountryList()
        this.getLanguageList()

    },
    methods: {
        async getLanguageList() {
            const { data } = await getLanguageList()
            this.languageList = data
        },
        async getCountryList() {
            const { data } = await getCountryList()
            this.countryList = data
        },
        formatDate(date) {
            const options = { year: 'numeric', month: '2-digit', day: '2-digit' };
            return new Date(date).toLocaleDateString('zh-CN', options);
        },
        async getStatistics() {
            if (!this.queryParams.dateRange.start) {
                const now = new Date();
                const today = now.toISOString().split('T')[0];
                const prevMonthDate = new Date(now.getFullYear(), now.getMonth() - 1, now.getDate());
                const startDate = prevMonthDate.toISOString().split('T')[0];

                this.queryParams = {
                    dateRange: {
                        start: startDate,
                        end: today,
                    },
                };
            }

            const query = {
                dateRange: this.queryParams.dateRange,
                country: this.queryParams.country,
                language: this.queryParams.language
            };

            const chartRefs = [this.$refs.chart1, this.$refs.chart2, this.$refs.chart3, this.$refs.chart4, this.$refs.chart5, this.$refs.chart6, this.$refs.chart7, this.$refs.chart8, this.$refs.chart9, this.$refs.chart10];

            const { data } = await getList(query);

            const counts = {};
            const questionIds = new Set();
            // 遍历数据，动态发现并统计各个 questionId 的答案
            data.forEach(item => {

                const responses = JSON.parse(item.questionnaireResponses);
                if (responses ) {
                    responses.forEach(response => {
                        const { questionId, answer_ids } = response;
                        questionIds.add(questionId);
                        if (!counts[questionId]) {
                            counts[questionId] = {};
                        }
                        answer_ids.forEach(answer => {
                            counts[questionId][answer] = (counts[questionId][answer] || 0) + 1;
                        });
                    });
                }
                
            });

            const interestQuestionIds = [...questionIds];
            this.currentList = interestQuestionIds;

            // 初始化和更新图表，仅在有数据时进行
            interestQuestionIds.forEach((questionId, index) => {
                // 准备图表数据
                const data = Object.entries(counts[questionId] || {}).map(([key, value]) => ({
                    name: key,
                    value
                }));

                if (data.length > 0) {
                    const chart = this.$echarts.init(chartRefs[index]);
                    chart.showLoading();

                    const option = {
                        title: { text: `${questionId} 分布`, left: 'center' },
                        tooltip: { trigger: 'item' },
                        legend: { bottom: '10%' },
                        series: [
                            {
                                name: questionId,
                                type: 'pie',
                                radius: '50%',
                                data,
                                emphasis: {
                                    itemStyle: {
                                        shadowBlur: 10,
                                        shadowOffsetX: 0,
                                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                                    }
                                },
                                label: {
                                    show: true,
                                    formatter: '{b}: {c} '  // 显示名字，值，和百分比
                                }
                            }
                        ]
                    };

                    chart.setOption(option);
                    chart.hideLoading();
                    chartRefs[index].style.display = 'block'; // 显示图表
                } else {
                    chartRefs[index].style.display = 'none'; // 隐藏无数据的图表
                }
            });

            // 隐藏多余的图表
            for (let i = interestQuestionIds.length; i < chartRefs.length; i++) {
                chartRefs[i].style.display = 'none';
            }
        }

        ,

        async getStatistics2() {

            if (!this.queryParams.dateRange.start) {
                // 获取当前时间
                const now = new Date();

                // 获取今天的日期：格式为 YYYY-MM-DD
                const today = now.toISOString().split('T')[0];

                // 获取上一个月的日期
                const prevMonthDate = new Date(now.getFullYear(), now.getMonth() - 1, now.getDate());
                const startDate = prevMonthDate.toISOString().split('T')[0]; // 开始日期
                // 赋值日期
                this.queryParams = {
                    dateRange: {
                        start: startDate,  // 得到的开始日期
                        end: today,        // 结束日期即今天
                    },
                };

            }
            let query = {
                dateRange: this.queryParams.dateRange,
                type: 'makeup'
            }

            this.chart2 = this.$echarts.init(this.$refs.chart2);
            // 显示加载动画
            this.chart2.showLoading(this.loadingOption);
            let { data } = await getFaceTokens(query);
            this.chartData = data;

            // 提取日期和计数数据
            const dates = data.map(item => item.date);
            const counts = data.map(item => item.total_tokens);
            const prompt_tokens = data.map(item => item.prompt_tokens);
            const completion_tokens = data.map(item => item.completion_tokens);
            this.option2 = {
                color: ['#3489FF'],
                grid: {
                    left: '5.5%',
                    right: '0%'
                },
                xAxis: [{
                    type: 'category',
                    data: dates, // 设置 x 轴数据
                    axisLine: {
                        show: false
                    },
                    axisTick: {
                        show: false
                    },
                    axisLabel: {
                        fontSize: 13,
                        color: '#999999',
                        margin: 13
                    },
                    splitLine: {
                        lineStyle: {
                            show: true,
                            color: '#DDDDDD'
                        }
                    }
                }],
                yAxis: [{
                    type: 'value',
                    axisLine: {
                        show: false
                    },
                    axisTick: {
                        show: false
                    },
                    axisLabel: {
                        fontSize: 13,
                        color: '#999999',
                        margin: 13
                    },
                    splitLine: {
                        lineStyle: {
                            show: true,
                            color: '#DDDDDD'
                        }
                    }
                }],
                series: [{
                    data: counts, // 设置 y 轴数据
                    type: 'line',
                    smooth: true,
                    areaStyle: {
                        color: {
                            type: 'linear',
                            x: 0,
                            y: 0,
                            x2: 0,
                            y2: 1,
                            colorStops: [{
                                offset: 0,
                                color: '#94cdfc' // 0% 处的颜色
                            }, {
                                offset: 1,
                                color: '#F4F7FF' // 100% 处的颜色
                            }]
                            // global: false // 缺省为 false
                        }
                    },
                    label: {
                        show: true,
                        position: 'top',
                    }
                }],
                tooltip: { // 鼠标悬浮提示框显示 X和Y 轴数据
                    trigger: 'axis',
                    backgroundColor: 'rgba(32, 33, 36,.7)',
                    borderColor: 'rgba(32, 33, 36,0.20)',
                    borderWidth: 1,
                    textStyle: { // 文字提示样式
                        color: '#fff',
                        fontSize: '12'
                    },
                    axisPointer: { // 坐标轴虚线
                        type: 'cross',
                        label: {
                            backgroundColor: '#6a7985'
                        }
                    },
                    formatter: function (params) {
                        const index = params[0].dataIndex;
                        return `
                                日期: ${dates[index]}<br/>
                                发-消耗: ${prompt_tokens[index]}<br/>
                                收-消耗: ${completion_tokens[index]}<br/>
                                总消耗: ${counts[index]}
                            `;
                    }
                },
                dataZoom: {
                    type: 'inside'
                }
            };
            setTimeout(() => {
                this.initChart2();
                this.chart2.hideLoading();

            })
        },
        async getStatistics3() {

            if (!this.queryParams.dateRange.start) {
                // 获取当前时间
                const now = new Date();

                // 获取今天的日期：格式为 YYYY-MM-DD
                const today = now.toISOString().split('T')[0];

                // 获取上一个月的日期
                const prevMonthDate = new Date(now.getFullYear(), now.getMonth() - 1, now.getDate());
                const startDate = prevMonthDate.toISOString().split('T')[0]; // 开始日期
                // 赋值日期
                this.queryParams = {
                    dateRange: {
                        start: startDate,  // 得到的开始日期
                        end: today,        // 结束日期即今天
                    }
                };

            }
            let query = {
                dateRange: this.queryParams.dateRange,
                type: 'product'
            }

            this.chart3 = this.$echarts.init(this.$refs.chart3);
            // 显示加载动画
            this.chart3.showLoading(this.loadingOption);
            let { data } = await getFaceTokens(query);
            this.chartData = data;

            // 提取日期和计数数据
            const dates = data.map(item => item.date);
            const counts = data.map(item => item.total_tokens);
            const prompt_tokens = data.map(item => item.prompt_tokens);
            const completion_tokens = data.map(item => item.completion_tokens);

            this.option3 = {
                color: ['#3489FF'],
                grid: {
                    left: '5.5%',
                    right: '0%'
                },
                xAxis: [{
                    type: 'category',
                    data: dates, // 设置 x 轴数据
                    axisLine: {
                        show: false
                    },
                    axisTick: {
                        show: false
                    },
                    axisLabel: {
                        fontSize: 13,
                        color: '#999999',
                        margin: 13
                    },
                    splitLine: {
                        lineStyle: {
                            show: true,
                            color: '#DDDDDD'
                        }
                    }
                }],
                yAxis: [{
                    type: 'value',
                    axisLine: {
                        show: false
                    },
                    axisTick: {
                        show: false
                    },
                    axisLabel: {
                        fontSize: 13,
                        color: '#999999',
                        margin: 13
                    },
                    splitLine: {
                        lineStyle: {
                            show: true,
                            color: '#DDDDDD'
                        }
                    }
                }],
                series: [{
                    data: counts, // 设置 y 轴数据
                    type: 'line',
                    smooth: true,
                    areaStyle: {
                        color: {
                            type: 'linear',
                            x: 0,
                            y: 0,
                            x2: 0,
                            y2: 1,
                            colorStops: [{
                                offset: 0,
                                color: '#94cdfc' // 0% 处的颜色
                            }, {
                                offset: 1,
                                color: '#F4F7FF' // 100% 处的颜色
                            }]
                            // global: false // 缺省为 false
                        }
                    },
                    label: {
                        show: true,
                        position: 'top',
                    }
                }],
                tooltip: { // 鼠标悬浮提示框显示 X和Y 轴数据
                    trigger: 'axis',
                    backgroundColor: 'rgba(32, 33, 36,.7)',
                    borderColor: 'rgba(32, 33, 36,0.20)',
                    borderWidth: 1,
                    textStyle: { // 文字提示样式
                        color: '#fff',
                        fontSize: '12'
                    },
                    axisPointer: { // 坐标轴虚线
                        type: 'cross',
                        label: {
                            backgroundColor: '#6a7985'
                        }
                    },
                    formatter: function (params) {
                        const index = params[0].dataIndex;
                        return `
                                日期: ${dates[index]}<br/>
                                发-消耗: ${prompt_tokens[index]}<br/>
                                收-消耗: ${completion_tokens[index]}<br/>
                                总消耗: ${counts[index]}
                            `;
                    }
                },
                dataZoom: {
                    type: 'inside'
                }
            };
            setTimeout(() => {
                this.initChart3();
                this.chart3.hideLoading();

            })
        },
        async getStatistics4() {
            if (!this.queryParams.dateRange.start) {
                // 获取当前时间
                const now = new Date();

                // 获取今天的日期：格式为 YYYY-MM-DD
                const today = now.toISOString().split('T')[0];

                // 获取上一个月的日期
                const prevMonthDate = new Date(now.getFullYear(), now.getMonth() - 1, now.getDate());
                const startDate = prevMonthDate.toISOString().split('T')[0]; // 开始日期
                // 赋值日期
                this.queryParams = {
                    dateRange: {
                        start: startDate,  // 得到的开始日期
                        end: today,        // 结束日期即今天
                    },

                };

            }
            let query = {
                dateRange: this.queryParams.dateRange,
            }

            this.chart4 = this.$echarts.init(this.$refs.chart4);
            // 显示加载动画
            this.chart4.showLoading(this.loadingOption);
            this.chart5 = this.$echarts.init(this.$refs.chart5);
            // 显示加载动画
            this.chart5.showLoading(this.loadingOption);
            // console.log(this.queryParams)
            let { data } = await getTokens(query);
            console.log(data)
            this.chartData = data;

            // 提取日期和计数数据
            const dates = data.map(item => item.date);
            const counts = data.map(item => item.total_tokens);
            const prompt_tokens = data.map(item => item.prompt_tokens);
            const completion_tokens = data.map(item => item.completion_tokens);
            const total_dollar = data.map(item => item.total_dollar);
            const prompt_dollar = data.map(item => item.prompt_dollar);
            const completion_dollar = data.map(item => item.completion_dollar);
            this.option4 = {
                color: ['#3489FF'],
                grid: {
                    left: '5.5%',
                    right: '0%'
                },
                xAxis: [{
                    type: 'category',
                    data: dates, // 设置 x 轴数据
                    axisLine: {
                        show: false
                    },
                    axisTick: {
                        show: false
                    },
                    axisLabel: {
                        fontSize: 13,
                        color: '#999999',
                        margin: 13
                    },
                    splitLine: {
                        lineStyle: {
                            show: true,
                            color: '#DDDDDD'
                        }
                    }
                }],
                yAxis: [{
                    type: 'value',
                    axisLine: {
                        show: false
                    },
                    axisTick: {
                        show: false
                    },
                    axisLabel: {
                        fontSize: 13,
                        color: '#999999',
                        margin: 13
                    },
                    splitLine: {
                        lineStyle: {
                            show: true,
                            color: '#DDDDDD'
                        }
                    }
                }],
                series: [{
                    data: counts, // 设置 y 轴数据
                    type: 'line',
                    smooth: true,
                    areaStyle: {
                        color: {
                            type: 'linear',
                            x: 0,
                            y: 0,
                            x2: 0,
                            y2: 1,
                            colorStops: [{
                                offset: 0,
                                color: '#94cdfc' // 0% 处的颜色
                            }, {
                                offset: 1,
                                color: '#F4F7FF' // 100% 处的颜色
                            }]
                            // global: false // 缺省为 false
                        }
                    },
                    label: {
                        show: true,
                        position: 'top',
                    }
                }],
                tooltip: { // 鼠标悬浮提示框显示 X和Y 轴数据
                    trigger: 'axis',
                    backgroundColor: 'rgba(32, 33, 36,.7)',
                    borderColor: 'rgba(32, 33, 36,0.20)',
                    borderWidth: 1,
                    textStyle: { // 文字提示样式
                        color: '#fff',
                        fontSize: '12'
                    },
                    axisPointer: { // 坐标轴虚线
                        type: 'cross',
                        label: {
                            backgroundColor: '#6a7985'
                        }
                    },
                    formatter: function (params) {
                        const index = params[0].dataIndex;
                        return `
                                日期: ${dates[index]}<br/>
                                发-消耗: ${prompt_tokens[index]}<br/>
                                收-消耗: ${completion_tokens[index]}<br/>
                                总消耗: ${counts[index]}
                            `;
                    }
                },
                dataZoom: {
                    type: 'inside'
                }
            };
            this.option5 = {
                color: ['#3489FF'],
                grid: {
                    left: '5.5%',
                    right: '0%'
                },
                xAxis: [{
                    type: 'category',
                    data: dates, // 设置 x 轴数据
                    axisLine: {
                        show: false
                    },
                    axisTick: {
                        show: false
                    },
                    axisLabel: {
                        fontSize: 13,
                        color: '#999999',
                        margin: 13
                    },
                    splitLine: {
                        lineStyle: {
                            show: true,
                            color: '#DDDDDD'
                        }
                    }
                }],
                yAxis: [{
                    type: 'value',
                    axisLine: {
                        show: false
                    },
                    axisTick: {
                        show: false
                    },
                    axisLabel: {
                        fontSize: 13,
                        color: '#999999',
                        margin: 13
                    },
                    splitLine: {
                        lineStyle: {
                            show: true,
                            color: '#DDDDDD'
                        }
                    }
                }],
                series: [{
                    data: total_dollar, // 设置 y 轴数据
                    type: 'line',
                    smooth: true,
                    areaStyle: {
                        color: {
                            type: 'linear',
                            x: 0,
                            y: 0,
                            x2: 0,
                            y2: 1,
                            colorStops: [{
                                offset: 0,
                                color: '#94cdfc' // 0% 处的颜色
                            }, {
                                offset: 1,
                                color: '#F4F7FF' // 100% 处的颜色
                            }]
                            // global: false // 缺省为 false
                        }
                    },
                    label: {
                        show: true,
                        position: 'top',
                    }
                }],
                tooltip: { // 鼠标悬浮提示框显示 X和Y 轴数据
                    trigger: 'axis',
                    backgroundColor: 'rgba(32, 33, 36,.7)',
                    borderColor: 'rgba(32, 33, 36,0.20)',
                    borderWidth: 1,
                    textStyle: { // 文字提示样式
                        color: '#fff',
                        fontSize: '12'
                    },
                    axisPointer: { // 坐标轴虚线
                        type: 'cross',
                        label: {
                            backgroundColor: '#6a7985'
                        }
                    },
                    formatter: function (params) {
                        const index = params[0].dataIndex;
                        return `
                                日期: ${dates[index]}<br/>
                                发-消耗: ≈$${prompt_dollar[index]}<br/>
                                收-消耗: ≈$${completion_dollar[index]}<br/>
                                总消耗: ≈$${total_dollar[index]}
                            `;
                    }
                },
                dataZoom: {
                    type: 'inside'
                }
            };
            setTimeout(() => {
                this.initChart4();
                this.chart4.hideLoading();
                this.initChart5();
                this.chart5.hideLoading();
            })
        },

        timeChange() {
            if (this.invalidDateRange) return; // 如果标志位为 true，则退出
            this.queryParams.dateRange.start = this.value1[0];
            this.queryParams.dateRange.end = this.value1[1];


            this.getStatistics();


        },
        getKeyByValue(object, value) {
            return Object.keys(object).find((key) => object[key] === value);
        },

        resetQuery() {
            this.queryParams.language = null;
            this.queryParams.country = null;
            this.queryParams.dateRange.start = null;
            this.queryParams.dateRange.end = null;
            this.queryParams.page = 1;
            this.value1 = "";
            this.str = '近30天'

            this.getStatistics();


        },
        async handleExport() {
            this.loading = true;
            let { data } = await calculateDailySuccessfulPayments(this.queryParams);

            const headers = {
                date: '日期',
                count: '续订人数'
            };
            const transformedData = data.map(item => {
                const newItem = {};
                for (const key in item) {
                    if (headers[key]) {
                        newItem[headers[key]] = item[key];
                    } else {
                        newItem[key] = item[key];
                    }
                }
                return newItem;
            });


            const ws = XLSX.utils.json_to_sheet(transformedData); // 将JSON转换成sheet
            const wb = XLSX.utils.book_new(); // 新建workbook
            XLSX.utils.book_append_sheet(wb, ws, "Sheet1"); // 在workbook中添加新的sheet
            XLSX.writeFile(wb, "MySpreadsheet.xlsx"); // 写文件并触发下载
        },
        async handleExport2() {
            this.loading = true;
            let { data } = await calculateDailySuccessfulRefunds(this.queryParams);

            const headers = {
                date: '日期',
                count: '退款人数'
            };
            const transformedData = data.map(item => {
                const newItem = {};
                for (const key in item) {
                    if (headers[key]) {
                        newItem[headers[key]] = item[key];
                    } else {
                        newItem[key] = item[key];
                    }
                }
                return newItem;
            });


            const ws = XLSX.utils.json_to_sheet(transformedData); // 将JSON转换成sheet
            const wb = XLSX.utils.book_new(); // 新建workbook
            XLSX.utils.book_append_sheet(wb, ws, "Sheet1"); // 在workbook中添加新的sheet
            XLSX.writeFile(wb, "MySpreadsheet.xlsx"); // 写文件并触发下载
        },
        async handleExport3() {
            this.loading = true;
            let { data } = await calculateConversionRate(this.queryParams);

            const headers = {
                date: '日期',
                initialCount: '试用',
                renewalCount: '续费人数',
                conversionRate: '转正率',
            };
            const transformedData = data.map(item => {
                const newItem = {};
                for (const key in item) {
                    if (headers[key]) {
                        newItem[headers[key]] = item[key];
                    } else {
                        newItem[key] = item[key];
                    }
                }
                return newItem;
            });


            const ws = XLSX.utils.json_to_sheet(transformedData); // 将JSON转换成sheet
            const wb = XLSX.utils.book_new(); // 新建workbook
            XLSX.utils.book_append_sheet(wb, ws, "Sheet1"); // 在workbook中添加新的sheet
            XLSX.writeFile(wb, "MySpreadsheet.xlsx"); // 写文件并触发下载
        },
        async handleExport4() {
            this.loading = true;
            let { data } = await calculateDailyDirectPurchases(this.queryParams);

            const headers = {
                date: '日期',
                count: '直接购买人数',
            };
            const transformedData = data.map(item => {
                const newItem = {};
                for (const key in item) {
                    if (headers[key]) {
                        newItem[headers[key]] = item[key];
                    } else {
                        newItem[key] = item[key];
                    }
                }
                return newItem;
            });


            const ws = XLSX.utils.json_to_sheet(transformedData); // 将JSON转换成sheet
            const wb = XLSX.utils.book_new(); // 新建workbook
            XLSX.utils.book_append_sheet(wb, ws, "Sheet1"); // 在workbook中添加新的sheet
            XLSX.writeFile(wb, "MySpreadsheet.xlsx"); // 写文件并触发下载
        },

        initChart1() {
            this.chartContainer1 = this.$echarts.init(document.querySelector('.police-count1'))
            this.chartContainer1.setOption(this.option1)
        },
        initChart2() {
            this.chartContainer2 = this.$echarts.init(document.querySelector('.police-count2'))
            this.chartContainer2.setOption(this.option2)
        },
        initChart3() {
            this.chartContainer3 = this.$echarts.init(document.querySelector('.police-count3'))
            this.chartContainer3.setOption(this.option3)
        },
        initChart4() {
            this.chartContainer4 = this.$echarts.init(document.querySelector('.police-count4'))
            this.chartContainer4.setOption(this.option4)
        },
        initChart5() {
            this.chartContainer5 = this.$echarts.init(document.querySelector('.police-count5'))
            this.chartContainer5.setOption(this.option5)
        },
    },
};
</script>
<style lang="scss" scoped>
.boxs {
    padding: 20px;
}

::v-deep.el-input.is-disabled .el-input__inner {
    color: #333 !important;
}

::v-deep.el-textarea.is-disabled .el-textarea__inner {
    color: #333 !important;
}

::v-deep .el-image {
    margin-right: 8px;
    border-radius: 4px;
}

.statistics-container {
    display: flex;
    flex-wrap: wrap;
    /* 自动换行 */
    gap: 10px;
    /* 数据块之间的间距 */
    padding: 10px;
    border: 1px solid #ddd;
    margin-bottom: 20px;
    font-size: 14px;
}

.item {
    background-color: #f9f9f9;
    padding: 8px;
    border: 1px solid #ddd;
    border-radius: 4px;
    display: inline-block;
    /* 使得每个元素成为一块 */
    white-space: nowrap;
    /* 防止单个元素中的文本换行 */
}

.police-count1,
.police-count2,
.police-count3,
.police-count4,
.police-count5,
.police-count6,
.police-count7,
.police-count8,
.police-count9,
.police-count10 {
    width: 48%;
    height: 700px;
    color: #000;
}


.loading .loading-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(255, 255, 255, 0.8);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1000;
}

.loading-spinner {
    border: 4px solid rgba(0, 0, 0, 0.1);
    border-top: 4px solid #3498db;
    border-radius: 50%;
    width: 40px;
    height: 40px;
    animation: spin 1s linear infinite;
}

@keyframes spin {
    0% {
        transform: rotate(0deg) !important;
    }

    100% {
        transform: rotate(360deg);
    }
}
</style> -->
<template>
    <div class="page">
        <el-container>
            <el-main>
                <div class="container">
                    <div class="socket flex_between">
                        <div class="message_list">
                            <div class="title fw700">聊天列表</div>
                            <div class="list_content">
                                <!-- 模拟动态渲染 -->
                                <div class="item_list shou" v-for="item in mockConversationList" :key="item.id">
                                    <div class="leftx flex_between">
                                        <div class="avatar_box">
                                            <img :src="item.userAvatar" class="icon" alt="">
                                            <div class="posi1" v-if="item.onLine === 1"></div>
                                            <div class="posi" v-else></div>
                                        </div>
                                        <div class="infox flex_column">
                                            <div class="flex_between">
                                                <div class="uname">{{ item.userName }}</div>
                                                <div class="rightx">{{ item.createTime }}</div>
                                            </div>
                                            <div class="flex_between" style="width: 100%;">
                                                <div class="text yichu">{{ item.content }}</div>
                                                <div style="margin-top: 8px;">
                                                    <el-badge v-if="item.serviceReadNum !== 0"
                                                        :value="item.serviceReadNum" :max="99" class="item">
                                                    </el-badge>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div v-if="mockConversationList.length === 0" class="flex_ccenter"
                                style="width: 100%;height: 100%;">
                                <el-empty style="transform: translateY(-50%);" description="暂无会话" />
                            </div>
                        </div>
                        <div class="message_content">
                            <div class="title fw700">{{ currentName }}</div>
                            <div class="content">
                                <el-scrollbar height="100%" wrap-class="wrap-class">
                                    <div class="scrollbar_box">
                                        <!-- 模拟动态渲染 -->
                                        <div class="message" v-for="item in mockMessageList" :key="item.id">
                                            <div class="timeFlag flex_center" v-if="item.flag">
                                                {{ item.createTime }}
                                            </div>
                                            <div class="message-item" :class="item.isItMe ? 'right' : 'left'">
                                                <img class="hearimg" :src="item.userAvatar" />
                                                <div class="content" v-if="item.type === 'message'">
                                                    <text>{{ item.content }}</text>
                                                </div>
                                                <div class="content contentType3" v-if="item.type === 'image'">
                                                    <img :src="item.imageUrl" class="message_img shou"
                                                        mode="widthFix" />
                                                </div>
                                                <div class="content contentType3" v-if="item.type === 'video'">
                                                    <div class="video_img" @click="openVideoTrue(item)">
                                                        <img :src="item.imageUrl" class="shou"
                                                            style="width: 100%;height:auto" />
                                                        <!-- <img src="@/assets/images/bofang.png" alt="" class="posi"
                                                            style="z-index: 2;"> -->
                                                        <div class="mask" style="width: 100%;height: 100%;z-index: 1;">
                                                        </div>
                                                        <div class="duration">{{ item.duration }}</div>
                                                    </div>
                                                </div>
                                            </div>
                                            <div v-if="item.type === 'back'" class="flex_ccenter"
                                                style="color: #999;font-size: 12px; height: 46px;margin-top: 10px;">
                                                客服撤回了一条消息
                                            </div>
                                        </div>
                                    </div>
                                </el-scrollbar>
                                <div class="send_box">
                                    <textarea style="font-size: 16px;" rows="" maxlength="300" cols=""
                                        v-model="msgContent" @keyup.enter="handlesend" placeholder="请输入"></textarea>
                                    <div class="send_btn shou" id="LAY-user-login-submit" @click="handlesend">
                                        发送
                                    </div>
                                </div>
                            </div>
                        </div>
                        <!-- <div class="message_info">
                            <div class="title fw700 c0">用户信息</div>
                            <div class="messageinfo_box">
                                <div class="item_info flex_" v-for="item in mockUserInfo" :key="item.id">
                                    <div class="key">{{ item.label }}</div>
                                    <div class="value">{{ item.value }}</div>
                                </div>
                            </div>
                        </div> -->
                    </div>
                </div>
            </el-main>
        </el-container>

        <div class="mask_box" v-if="openVideo">
            <span class="el-image-viewer__btn el-image-viewer__close">×</span>
            <div class="posiVideo">
                <video :src="videoUrl" controls></video>
            </div>
        </div>
    </div>
</template>

<script>
export default {
    data() {
        return {
            mockConversationList: [
                { id: 1, userAvatar: 'https://via.placeholder.com/50', userName: '用户1', createTime: '2023-10-01 10:00', content: '你好', serviceReadNum: 0, onLine: 1 },
                { id: 2, userAvatar: 'https://via.placeholder.com/50', userName: '用户2', createTime: '2023-10-02 11:00', content: '你好吗', serviceReadNum: 1, onLine: 0 }
            ],
            mockMessageList: [
                { id: 1, userAvatar: 'https://via.placeholder.com/45', content: '你好，有什么可以帮助你的？', type: 'message', isItMe: true, createTime: '2023-10-01 10:00', flag: true },
                { id: 2, userAvatar: 'https://via.placeholder.com/45', content: '你好，我想了解一下你们的产品。', type: 'message', isItMe: false, createTime: '2023-10-01 10:05', flag: true },
                { id: 3, imageUrl: 'https://via.placeholder.com/200', type: 'image', isItMe: true, createTime: '2023-10-01 10:10', flag: true },
                { id: 4, imageUrl: 'https://via.placeholder.com/200', videoUrl: 'https://via.placeholder.com/200', duration: '0:30', type: 'video', isItMe: false, createTime: '2023-10-01 10:15', flag: true }
            ],
            mockUserInfo: [
                { id: 1, label: '会员姓名：', value: '张三' },
                { id: 2, label: '手机号：', value: '13800138000' },
                { id: 3, label: 'IP：', value: '192.168.1.1' },
                { id: 4, label: 'IP属地：', value: '北京市' },
                { id: 5, label: '余额：', value: '100.00' },
                { id: 6, label: '余额宝：', value: '50.00' },
                { id: 7, label: '总充值：', value: '200.00' },
                { id: 8, label: '总提现：', value: '100.00' },
                { id: 9, label: '个人项目累计投资：', value: '300.00' },
                { id: 10, label: '个人项目累计收益：', value: '50.00' }
            ],
            currentName: '当前聊天用户',
            msgContent: '',
            openVideo: false,
            videoUrl: ''
        };
    },
    methods: {
        openVideoTrue(item) {
            this.videoUrl = item.videoUrl;
            this.openVideo = true;
        },
        closeVideo() {
            this.openVideo = false;
        }
    }
};
</script>

<style lang="scss" scoped>
.video_img_000 {
    border-radius: 4px;
    width: 200px;
    height: 260px;
    background-color: #000;
    position: relative;
    overflow: hidden;
    display: block;
    cursor: pointer;

    .posi {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 40px;
        height: 40px;
    }
}

.el-scrollbar {
    height: 70%;
}

.yichu {
    width: 120px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.context-menu {
    position: absolute;
    top: -35px;
    right: 60px;
    background: #FFF;
    color: #34495E;
    min-width: 100px;
    box-shadow: 0px 2px 4px 0px rgba(0, 0, 0, 0.2);
    border-radius: 2px;
    cursor: pointer;
    z-index: 1002;

    &>ul {
        padding: 0px 0px !important;
        height: 10px;

        &>li {
            text-align: center;
            padding: 0px 4px;
            font-size: 12px;
        }

        .disabled {
            color: #888585;
            pointer-events: none;
        }
    }
}

.el-dropdown-menu {
    width: 250px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.example-showcase .el-dropdown-link {
    cursor: pointer;
    color: var(--el-color-primary);
    display: flex;
    align-items: center;
}

.tips_item {
    padding: 10px 0;
    width: 100%;
    border-bottom: 1px solid #f3f3f3;

    .tip {
        width: 210px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }
}

.mask_box {
    position: fixed;
    left: 0;
    top: 0;
    bottom: 0;
    right: 0;
    background: rgba(0, 0, 0, 0.5) !important;
    z-index: 2500;

    .posiVideo {
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
    }
}

.mask {
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    background: #000;
    opacity: .1;
}

textarea {
    outline: none;
    border: 0;
    outline: none;
    box-shadow: none;
    width: 100%;
    height: 80%;
    resize: none;
    padding: 8px;
}

.container {
    font-family: PingFang SC;
    box-sizing: border-box;
}

.timeFlag {
    color: #999;
    font-size: 12px;
    margin-bottom: 10px;
}

.title {
    font-family: PingFang SC;
    border-bottom: 1px solid #f6f6f6;
    padding-bottom: 15px;
    margin: 0;
    color: #333;
}

.socket {
    overflow: hidden;
    box-shadow: 0 0 29px 0 hsl(0deg 0% 74% / 30%);
    border-radius: 10px;
    height: 85vh;
    min-width: 1100px;
    max-width: 1400px;
    margin: auto;
    box-sizing: border-box;
}

.message_list {
    height: 100%;
    width: 270px;
    min-width: 270px;
    border-right: 1px solid #f5f5f5;
    box-sizing: border-box;

    .title {
        margin: 0;
        padding: 10px;
        padding-bottom: 15px;
        color: #333;
    }

    .list_content {
        min-width: 270px;
        height: 95%;
        overflow-y: scroll;
        box-sizing: border-box;

        .avatar_box {
            position: relative;
            width: 50px;
            height: 50px;
            border-radius: 50%;
            margin-right: 10px;

            .posi {
                position: absolute;
                bottom: 0;
                right: 0;
                width: 10px;
                height: 10px;
                border-radius: 50%;
                background-color: #ccc;
            }

            .posi1 {
                position: absolute;
                bottom: 0;
                right: 0;
                width: 10px;
                height: 10px;
                border-radius: 50%;
                background-color: lightgreen;
            }
        }

        .item_list {
            box-sizing: border-box;
            width: 100%;
            border-bottom: 1px solid #f6f6f6;
            align-items: flex-start;
            padding: 10px;

            .leftx {
                .icon {
                    width: 50px;
                    height: 50px;
                    border-radius: 50%;
                    margin-right: 10px;
                }

                .infox {
                    height: 50px;
                    flex: 1;

                    .uname {
                        font-size: 15px;
                    }

                    .text {
                        font-size: 12px;
                    }
                }
            }

            .rightx {
                font-size: 12px;
                color: #999;
            }
        }

        .changeItem {
            background-color: #cfd8dc;
        }

        .item:last-child {
            border: 0;
        }
    }

    .list_content::-webkit-scrollbar {
        display: none;
    }
}

.message_info {
    border-left: 1px solid #f6f6f6;
    height: 100%;
    width: 300px;

    .title {
        margin: 0;
        padding: 10px;
        padding-bottom: 15px;
        color: #333;
    }
}

.message_content {
    flex: 1;
    height: 100%;

    .title {
        font-family: PingFang SC;
        border-bottom: 1px solid #f6f6f6;
        padding: 10px;
        padding-bottom: 15px;
        margin: 0;
        color: #333;
    }

    .content {
        color: #fff;
        height: 95%;
        width: 100%;

        .scrollbar_box {
            flex: 1;
            overflow-y: scroll;
            height: 70%;

            .message {
                padding: 13px 20px;
                padding-top: 30px;
            }

            .message-item {
                display: flex;
                justify-content: flex-start;
                align-items: flex-start;
                align-content: flex-start;
                flex-wrap: nowrap;
                flex-direction: row;
                position: relative;

                .hearimg {
                    width: 45px;
                    height: 45px;
                    border-radius: 50%;
                }

                .content {
                    padding: 10px;
                    max-width: 500px;
                    border-radius: 10px;
                    font-size: 15px;
                }

                .contentType2 {
                    display: flex;
                    flex-direction: row;
                    align-items: center;

                    .voice_icon {
                        height: 34px;
                        width: 24px;
                        background-repeat: no-repeat;
                        background-size: 100%;
                        color: #ffffff;
                    }

                    .voice_icon_right_an {
                        animation: voiceAn_right 1s linear alternate infinite;
                    }

                    .voice_icon_left_an {
                        animation: voiceAn_left 1s linear alternate infinite;
                    }
                }

                .contentType3 {
                    padding: 0;
                    border-radius: 2px;
                    background-color: transparent !important;

                    .message_img {
                        border-radius: 4px;
                        height: auto;
                        display: block;
                        cursor: pointer;
                        max-width: 200px;
                    }

                    .video_img {
                        position: relative;
                        overflow: hidden;
                        border-radius: 4px;
                        height: auto;
                        display: block;
                        cursor: pointer;
                        max-width: 200px;

                        .posi {
                            position: absolute;
                            top: 50%;
                            left: 50%;
                            transform: translate(-50%, -50%);
                            width: 40px;
                            height: 40px;
                        }

                        .duration {
                            position: absolute;
                            bottom: 4px;
                            right: 8px;
                            color: #fff;
                            font-size: 12px;
                        }
                    }
                }

                .contentType3::after {
                    border: none !important;
                    display: none !important;
                }

                .content-type-right {
                    flex-direction: row-reverse;
                }

                &.right {
                    flex-direction: row-reverse;
                    color: #ffffff;

                    .hearimg {
                        margin-left: 14px;
                    }

                    .content {
                        background: var(--el-menu-active-color);
                        border-radius: 10px 0px 10px 10px;
                        word-break: break-all;
                        line-height: 26px;
                        padding: 10px;
                    }
                }

                &.left {
                    .hearimg {
                        margin-right: 14px;
                    }

                    .content {
                        background: var(--el-menu-active-color);
                        border-radius: 0px 10px 10px 10px;
                        word-break: break-all;
                        line-height: 26px;
                        padding: 8px;
                    }

                    .contentType3 {
                        margin: 0;
                        padding: 0;
                    }
                }
            }
        }

        .scrollbar_box::-webkit-scrollbar {
            display: none;
        }

        .send_box {
            position: relative;
            padding: 10px;
            height: 30%;
            border-top: 1px solid #f6f6f6;
            box-sizing: border-box;

            .drawer {
                margin-left: 30px;
                padding: 4px 10px;
                background-color: var(--el-menu-active-color);
                color: #fff;
                font-size: 12px;
                border-radius: 4px;
            }

            .send_btn {
                position: absolute;
                bottom: 20px;
                right: 10px;
                width: 70px;
                height: 35px;
                background-color: var(--el-menu-active-color);
                color: #fff;
                font-size: 15px;
                line-height: 35px;
                text-align: center;
                border-radius: 4px;
            }
        }
    }
}

.messageinfo_box {
    padding: 14px;

    .item_info {
        margin-bottom: 20px;
        font-size: 15px;

        .key {
            color: #333;
            margin-right: 10px;
        }

        .value {
            color: #666;
        }
    }
}

.kong {
    height: 47px;
}
</style>